<?php
class EventManager_Service_Authentication{
	/**
	 *
	 * @var unknown_type
	 */
	protected $_authAdapter;
	/**
	 * @var unknown_type
	 */
	protected $_userModel;
	/**
	 *
	 * @var unknown_type
	 */
	protected $_auth;
        /**
         *
         * @var <type> 
         */
        protected $user;

	/**
	 *
	 * @param EventManager_Model_User $userModel
	 * @return unknown_type
	 */
	public function __construct(EventManager_Model_User $userModel= null){
		$this->_userModel = null === $userModel ? new EventManager_Model_User() : $userModel;
	}

	/**
	 *
	 * @param $credentials
	 * @return boolean
	 */
	public function authenticate($credentials){
		$adapter 	= $this->getAuthAdapter($credentials);
		$auth		= $this->getAuth();
		$result		= $auth->authenticate($adapter);

		if(!$result->isValid()){
			return false;
		}
                if(isset($credentials['usr_email'])){

                    $user = $this->_userModel->getUserByEmail($credentials['usr_email']);
                    $auth->getStorage()->write($user);
                    return true;
                }
                
                
                //return false;
	}
	/**
	 *
	 * @return unknown_type
	 */
	public function getAuth(){
		if(null === $this->_auth){
			$this->_auth = Zend_Auth::getInstance();
		}
		return $this->_auth;
	}
	/**
	 *
	 * @return unknown_type
	 */
	public function getIdentity(){
		$auth = $this->getAuth();
		if($auth->hasIdentity()){
			return $auth->getIdentity();
		}
		return false;
	}
	/**
	 *
	 * @return unknown_type
	 */
	public function clear(){
		$this->getAuth()->clearIdentity();
	}
	/**
	 *
	 * @param $values
	 * @return unknown_type
	 */
	public function getAuthAdapter($values){
		if(null === $this->_authAdapter){
			$authAdapter = new Zend_Auth_Adapter_DbTable(
			Zend_Db_Table_Abstract::getDefaultAdapter(),
				'user',
				'usr_email',
				'usr_password'
				);
				$this->setAuthAdapter($authAdapter);
				if (isset($values['usr_email']) && isset($values['usr_password'])){
                                    $this->_authAdapter->setIdentity($values['usr_email']);
                                    $this->_authAdapter->setcredential($values['usr_password']);
                                    $this->_authAdapter->setCredentialTreatment('SHA1(CONCAT(?,salt))');
                                }
		}
		return $this->_authAdapter;
	}

	public function setAuthAdapter(Zend_Auth_Adapter_Interface $adapter){
		$this->_authAdapter = $adapter;
	}
}